{extend name="layout/base" /}

{block name="css"}
<style>
/* 统计卡片样式 */
.management-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 32px;
}

.stat-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.2);
    position: relative;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    backdrop-filter: blur(10px);
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--primary-color), #667eea, #764ba2);
    border-radius: 16px 16px 0 0;
}

.stat-card:hover {
    transform: translateY(-8px) scale(1.02);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    border-color: rgba(102, 126, 234, 0.3);
}

.stat-card:nth-child(1)::before {
    background: linear-gradient(90deg, #667eea, #764ba2);
}

.stat-card:nth-child(2)::before {
    background: linear-gradient(90deg, #f093fb, #f5576c);
}

.stat-card:nth-child(3)::before {
    background: linear-gradient(90deg, #4facfe, #00f2fe);
}

.stat-card:nth-child(4)::before {
    background: linear-gradient(90deg, #43e97b, #38f9d7);
}

.stat-icon {
    font-size: 32px;
    display: block;
    margin-bottom: 12px;
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.stat-number {
    font-size: 28px;
    font-weight: 700;
    color: #2c3e50;
    display: block;
    margin-bottom: 4px;
    background: linear-gradient(135deg, #2c3e50, #3498db);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.stat-label {
    font-size: 14px;
    color: #6c757d;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: block;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .management-stats {
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
    }
    
    .stat-card {
        padding: 20px;
    }
    
    .stat-icon {
        font-size: 28px;
    }
    
    .stat-number {
        font-size: 24px;
    }
    
    .stat-label {
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .management-stats {
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }
    
    .stat-card {
        padding: 16px;
        text-align: center;
    }
    
    .stat-icon {
        font-size: 24px;
        margin-bottom: 8px;
    }
    
    .stat-number {
        font-size: 20px;
    }
    
    .stat-label {
        font-size: 12px;
    }
}
</style>
{/block}

{block name="content"}
<div class="page-container">
    <div class="page-header">
        <h1 class="page-title">
            <span>🏢</span>
            部门管理
        </h1>
        <p class="page-subtitle">管理公司组织架构，为名片生成提供部门信息支持</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="management-stats">
        <div class="stat-card">
            <span class="stat-icon">🏢</span>
            <span class="stat-number" id="totalDepartments">0</span>
            <span class="stat-label">总部门数</span>
        </div>
        <div class="stat-card">
            <span class="stat-icon">👥</span>
            <span class="stat-number" id="totalPositions">0</span>
            <span class="stat-label">关联岗位</span>
        </div>
        <div class="stat-card">
            <span class="stat-icon">📈</span>
            <span class="stat-number" id="recentlyAdded">0</span>
            <span class="stat-label">本月新增</span>
        </div>
        <div class="stat-card">
            <span class="stat-icon">⚡</span>
            <span class="stat-number">实时</span>
            <span class="stat-label">数据同步</span>
        </div>
    </div>
    
    <!-- 操作区域 -->
    <div style="margin-bottom: 30px;">
        <button class="btn btn-primary" onclick="showAddModal()">
            <span>➕</span>
            添加部门
        </button>
        <button class="btn btn-outline-secondary" onclick="loadDepartments()">
            <span>🔄</span>
            刷新数据
        </button>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-wrapper">
        <div class="table-header">
            <h3 class="table-title">
                <span>📋</span>
                部门列表
            </h3>
        </div>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>部门名称</th>

                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="departmentTableBody">
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 40px;">
                            <div>加载中...</div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 部门编辑模态框 -->
<div id="departmentModal" class="modal hidden">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle" class="modal-title">添加部门</h2>
            <button class="close-btn" onclick="hideModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="departmentForm">
                <input type="hidden" id="departmentId">
                
                <div class="form-group">
                    <label class="form-label" for="departmentName">部门名称 <span class="required">*</span></label>
                    <input type="text" id="departmentName" name="name" class="form-control" placeholder="请输入部门名称" required>
                </div>
                

            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline-secondary" onclick="hideModal()">取消</button>
            <button class="btn btn-primary" onclick="saveDepartment()">
                <span>💾</span>
                保存
            </button>
        </div>
    </div>
</div>
{/block}

{block name="js"}
<script>
// 全局变量
var departments = [];

// 显示添加模态框
function showAddModal() {
    console.log('显示添加模态框');
    document.getElementById('modalTitle').textContent = '添加部门';
    document.getElementById('departmentId').value = '';
    document.getElementById('departmentName').value = '';

    
    var modal = document.getElementById('departmentModal');
    modal.classList.remove('hidden');
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    setTimeout(function() {
        document.getElementById('departmentName').focus();
    }, 300);
}

// 隐藏模态框
function hideModal() {
    console.log('隐藏模态框');
    var modal = document.getElementById('departmentModal');
    modal.classList.add('hidden');
    modal.style.display = 'none';
    document.body.style.overflow = '';
}

// 编辑部门
function editDepartment(id) {
    console.log('编辑部门:', id);
    var dept = departments.find(function(item) { return item.id == id; });
    if (dept) {
        document.getElementById('modalTitle').textContent = '编辑部门';
        document.getElementById('departmentId').value = dept.id;
        document.getElementById('departmentName').value = dept.name;

        
        var modal = document.getElementById('departmentModal');
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        
        setTimeout(function() {
            document.getElementById('departmentName').focus();
        }, 300);
    } else {
        alert('部门不存在');
    }
}

// 删除部门
function deleteDepartment(id) {
    console.log('删除部门:', id);
    
    if (confirm('确定要删除这个部门吗？')) {
        fetch('/department/delete/' + id, {
            method: 'POST'
        })
        .then(function(response) { 
            return response.json(); 
        })
        .then(function(data) {
            if (data.code === 1) {
                loadDepartments();
            } else {
                alert('删除失败: ' + data.msg);
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
            alert('删除失败');
        });
    }
}

// 保存部门
function saveDepartment() {
    console.log('保存部门');
    
    var id = document.getElementById('departmentId').value;
    var name = document.getElementById('departmentName').value.trim();

    
    // 验证
    if (!name) {
        alert('部门名称不能为空');
        document.getElementById('departmentName').focus();
        return;
    }
    
    var data = new FormData();
    data.append('name', name);

    
    var url = id ? '/department/update/' + id : '/department/add';
    
    fetch(url, {
        method: 'POST',
        body: data
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.code === 1) {
            hideModal();
            loadDepartments();
        } else {
            alert((id ? '更新失败: ' : '添加失败: ') + data.msg);
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
        alert(id ? '更新失败' : '添加失败');
    });
}

// 加载部门列表
function loadDepartments() {
    console.log('加载部门列表');
    
    fetch('/department/getList')
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.code === 1) {
                departments = data.data;
                renderDepartmentTable();
            } else {
                alert('加载部门列表失败: ' + data.msg);
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
            alert('加载部门列表失败');
        });
}

// 更新统计数据
function updateStats() {
    // 更新总部门数
    document.getElementById('totalDepartments').textContent = departments.length;
    
    // 计算本月新增部门数
    var thisMonth = new Date().getMonth() + 1;
    var thisYear = new Date().getFullYear();
    var recentlyAdded = departments.filter(function(dept) {
        var createDate = new Date(dept.create_time);
        return createDate.getMonth() + 1 === thisMonth && createDate.getFullYear() === thisYear;
    }).length;
    document.getElementById('recentlyAdded').textContent = recentlyAdded;
    
    // 获取关联岗位数（需要调用岗位接口）
    fetch('/position/getList')
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.code === 1) {
                document.getElementById('totalPositions').textContent = data.data.length;
            }
        })
        .catch(function(error) {
            console.log('获取岗位数据失败:', error);
            document.getElementById('totalPositions').textContent = '-';
        });
}

// 渲染部门表格
function renderDepartmentTable() {
    var tbody = document.getElementById('departmentTableBody');
    
    // 更新统计数据
    updateStats();
    
    if (departments.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; padding: 40px;"><div>暂无部门数据</div><button class="btn btn-primary" onclick="showAddModal()" style="margin-top: 16px;"><span>➕</span> 添加第一个部门</button></td></tr>';
        return;
    }
    
    var html = '';
    for (var i = 0; i < departments.length; i++) {
        var dept = departments[i];
        html += '<tr>';
        html += '<td><strong>#' + dept.id + '</strong></td>';
        html += '<td><div style="font-weight: 600; color: #2c3e50;">' + dept.name + '</div></td>';

        html += '<td><div style="font-size: 13px; color: #6c757d;">' + formatDate(dept.create_time) + '</div></td>';
        html += '<td><div class="table-actions">';
        html += '<button class="btn btn-sm btn-warning" onclick="editDepartment(' + dept.id + ')" title="编辑"><span>✏️</span></button>';
        html += '<button class="btn btn-sm btn-danger" onclick="deleteDepartment(' + dept.id + ')" title="删除"><span>🗑️</span></button>';
        html += '</div></td>';
        html += '</tr>';
    }
    
    tbody.innerHTML = html;
}

// 格式化日期
function formatDate(dateString) {
    var date = new Date(dateString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，开始加载部门数据');
    loadDepartments();
});
</script>
{/block}